package com.eastcom.groovy.task

import com.eastcom.groovy.context.TaskContext
import com.eastcom.groovy.provider.SpringContextProvider
import com.eastcom.groovy.provider.TaskProvider
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.quartz.CronScheduleBuilder
import org.quartz.CronTrigger
import org.quartz.JobBuilder
import org.quartz.JobDetail
import org.quartz.Scheduler
import org.quartz.SchedulerException
import org.quartz.TriggerBuilder
import org.quartz.TriggerKey
import org.springframework.stereotype.Component

/**
 * Created by yuanyue on 2014-08-02.
 */
@Component("groovyTaskManager")
class TaskManager{
//    ITaskProvidor providor
    static  Log logger = LogFactory.getLog(TaskManager.class)
    Scheduler scheduler

    TaskManager() {

    }

    void scheduleJob(String xmlPath) {

        TaskContext.getAllTask().each {
            TriggerKey triggerKey = TriggerKey.triggerKey(it.getJobName(), it.getJobGroup());

            //获取trigger，即在spring配置文件中定义的 bean id="myTrigger"
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

            //不存在，创建一个
            if (null == trigger) {
                JobDetail jobDetail = JobBuilder.newJob(it.class)
                        .withIdentity(it.getJobName(), it.getJobGroup()).build();
                jobDetail.getJobDataMap().put("scheduleJob", it);

                //表达式调度构建器
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(it.getCronExpression());

//                System.out.println(it.getCronExpression());
                logger.debug("调度任务["+it.jobId+"]"+" "+it.cronExpression)
                //按新的cronExpression表达式构建一个新的trigger
                trigger = TriggerBuilder.newTrigger().withIdentity(it.getJobName(), it.getJobGroup()).withSchedule(scheduleBuilder).build();
                try{
                    scheduler.scheduleJob(jobDetail, trigger);
                }catch (SchedulerException e){
                    logger.debug("schedule error!")
                }

            } else {
                // Trigger已存在，那么更新相应的定时设置
                //表达式调度构建器
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(it.getCronExpression());

                //按新的cronExpression表达式重新构建trigger
                trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
                        .withSchedule(scheduleBuilder).build();

                //按新的trigger重新设置job执行
                scheduler.rescheduleJob(triggerKey, trigger);
            }
        }

    }

    void loadTask(List<String> xmlPath) {
        TaskProvider provider = new TaskProvider();
        provider.loadTaskClosure(xmlPath);
        //schedulerFactoryBean 由spring创建注入
        scheduler = (Scheduler) SpringContextProvider.getBean("schedulerFactoryBean");
        for(int i = 0; i < xmlPath.size(); i++){
            String path = xmlPath.get(i)
            scheduleJob(path)
        }
        scheduler.start();
    }
}
